<template>
  <Layout>
    <Form ref="form1" :model="form1" :label-width="120">
      <Row :gutter="16" class="query-form2" v-show="!switchFlag">
        <Col span="8">
          <FormItem label="作品名称：" prop="worksTitle">
            <Input class="query-form-el" type="text" v-model="form1.worksTitle"></Input>
          </FormItem>
        </Col>
        <Col span="8">

          <FormItem label="作品类型：">
            <Select filterable v-model="form1.worksType">
              <Option v-for="item in woksTypeList" :value="item.value" :key="item.value">{{ item.name }}
              </Option>
            </Select>
          </FormItem>
        </Col>
        <Col span="8">
          <div style="float: right;">
            <Button class="ivu-btn-query" icon="md-search" @click="query1">查询</Button>
            <Button class="ivu-btn-reset" style="margin-left: 10px" @click="reset">重置</Button>
            <Button @click="switchQuery(true)" style="margin-left: 5px" class="ivu-btn-switch2" type="text">
              展开
              <Icon type="ios-arrow-down"/>
            </Button>
          </div>
        </Col>
      </Row>
      <Row :gutter="16" v-show="switchFlag" class="query-form2">
        <Col span="8">
          <FormItem label="作品名称：" prop="worksTitle">
            <Input class="query-form-el" type="text" v-model="form1.worksTitle"></Input>
          </FormItem>
        </Col>
        <Col span="8">
          <FormItem label="作品类型：">
            <Select filterable v-model="form1.worksType">
              <Option v-for="item in woksTypeList" :value="item.value" :key="item.value">{{ item.name }}
              </Option>
            </Select>
          </FormItem>
        </Col>
        <Col span="8">
          <FormItem label="活动名称：">
            <Input type="text" v-model="form1.activityName"></Input>
          </FormItem>
        </Col>
      </Row>
      <Row :gutter="16" v-show="switchFlag" class="query-form2">
        <Col span="8">
          <FormItem label="活动主题：" prop="themeName">
            <Input class="query-form-el" type="text" v-model="form1.themeName"></Input>
          </FormItem>
        </Col>
        <Col span="8">
          <FormItem label="二级集团：">
            <two-level-org orgCode v-model="form1.twoLevelOrgId"></two-level-org>
          </FormItem>
        </Col>
        <Col span="8">
          <FormItem label="所属单位：" prop="orgName">
            <!--            <cascader-dom class="query-form-el" ref='queryOrgCascader'
                                      @setOrgname='(orgName)=>{form1.orgName = orgName}' :orgTree="true"
                                      :setCurrentName="{label:form1.companyName,value:form1.companyId}"
                                      style="width: 100%;"></cascader-dom>-->
            <company-select v-model="form1.orgName" class="w"></company-select>
          </FormItem>
        </Col>
      </Row>
      <Row :gutter="16" v-show="switchFlag" class="query-form2">
        <Col span="8">
          <FormItem label="发布时间：">
            <Date-picker type="daterange" style="width: 95%" v-model="createDate"/>
          </FormItem>
        </Col>
        <Col span="8">
          <FormItem label="状态：">
            <Select filterable v-model="form1.top">
              <Option v-for="item in topList" :value="item.value" :key="item.value">{{ item.name }}
              </Option>
            </Select>
          </FormItem>
        </Col>
        <Col span="8">
          <FormItem label="作者：" prop="createUserName">
            <Input type="text" v-model="form1.createUserName"></Input>
          </FormItem>
        </Col>

      </Row>
      <Row :gutter="16" v-show="switchFlag" class="query-form2">
        <Col offset="16" span="8">
          <div style="float: right;">
            <Button class="ivu-btn-query" icon="md-search" @click="query1">查询</Button>
            <Button class="ivu-btn-reset" style="margin-left: 10px" @click="reset">重置</Button>
            <Button @click="switchQuery(false)" style="margin-left: 10px" class="ivu-btn-switch2"
                    type="text">收起
              <Icon type="ios-arrow-up"/>
            </Button>
          </div>
        </Col>
      </Row>
      <Row class="query-form">
        <Col span="24">
          <Button size="large" class="ivu-btn-add" icon="md-add" @click="addInfo">新增</Button>
          <DownloadButton :api="exportUrl" :export-form-before="exportBefore" :query-form="form1"></DownloadButton>
        </Col>
      </Row>
    </Form>

    <Table ref='table' :height="tableHeight" :loading="loading" @on-selection-change='getSelectRows'
           border :columns="columns1" :data="dataTable" show-summary :summary-method="amountTo"
           @on-sort-change="sortChange">
    </Table>

    <Row style="margin-right:10px;">
      <Col span="24">
        <Page style="float: right" :total="pagedata.total" :page-size="pagedata.pageSize"
              @on-change="pageChange" @on-page-size-change="pageSizeChange" :page-size-opts="pageSizeArray"
              show-total show-sizer show-elevator/>
      </Col>
    </Row>

    <Modal :title="add?'作品信息新增':'作品信息修改'" :transfer=false v-model="model1" :width=1300>
      <Spin fix v-if="showLoading">
        <Icon type="ios-loading" size=18 class="demo-spin-icon-load"></Icon>
        <div>加载中</div>
      </Spin>
      <Form ref="form1datacopy" :model="form1datacopy" :rules="ruleCustom" label-position="top">
        <Row type="flex" justify="space-around" class="code-row-bg">
          <Col span="11">
            <FormItem label="作品名称：" prop="worksTitle">
              <Input type="text" v-model="form1datacopy.worksTitle"></Input>
            </FormItem>
          </Col>
          <Col span="11">
            <FormItem label="活动主题：">
              <!--              <Select filterable v-model="form1datacopy.programmeId"
                                    @on-change="selectActivityList">
                              <Option v-for="item in themeList" :value="item.programmeId" :key="item.id">
                                {{ item.themeName }}
                              </Option>
                            </Select>-->
              <Input type="text" v-model="form1datacopy.themeName" readonly>
                <Button slot="append" @click="activityForSelectIsTrue"
                        icon="ios-search"></Button>
              </Input>
            </FormItem>
          </Col>
        </Row>
        <Row type="flex" justify="space-around" class="code-row-bg">
          <Col span="11">
            <FormItem label="活动内容：">
              <Select filterable v-model="form1datacopy.activityId">
                <Option v-for="item in activityList" :value="item.id" :key="item.id">
                  {{ item.activityContent }}
                </Option>
              </Select>
            </FormItem>
          </Col>
          <Col span="11">
            <FormItem label="作品类型：" prop="worksType">
              <Select v-model="form1datacopy.worksType" @on-change="selectWorksType">
                <Option v-for="item in woksTypeList" :value="item.value" :key="item.value" >
                  {{ item.name }}
                </Option>
              </Select>
            </FormItem>
          </Col>
        </Row>
        <Row type="flex" justify="space-around" class="code-row-bg"  v-if="form1datacopy.worksType=='0'">
          <Col span="23">
            <FormItem label="内容：" prop="tpshow">
              <quill-editor ref="myTextEditor"
                            v-model="form1datacopy.tpshow"
                            :options="editorOption"
                            style="height:500px;padding-bottom: 50px"></quill-editor>
              <Upload class="edit-img"  :action="upImg" :show-upload-list="false"
                      :before-upload="uploadExcel"
                      :format="['jpg','jpeg','png']"
                      accept="image/jpeg,image/jpg,image/png"
                      :headers='{"Authorization": token}'>
                <Button type="ghost" icon="ios-cloud-upload-outline">上传文件</Button>
              </Upload>
            </FormItem>

          </Col>
        </Row>
        <Row type="flex" justify="space-around" class="code-row-bg" v-else>
          <Col span="23">
            <FormItem label="描述：" prop="tpshow">
              <Input type="textarea" :rows="2" v-model="form1datacopy.tpshow"></Input>
            </FormItem>
          </Col>
        </Row>
        <Row v-if="form1datacopy.worksType=='0'" type="flex" justify="space-around" class="code-row-bg">
          <Col span="23">
            <FormItem label="封面：" prop="imgs">
              <Upload
                  ref="upload"
                  type="drag"
                  :show-upload-list="false"
                  :action="upUrl"
                  :before-upload="beforeUploadImg"
              >
                <div style="height: 60px">
                  <Icon type="ios-cloud-upload" size="24" style="color: #3399ff"></Icon>
                  <p> 请上传 jpg，jpeg，png 格式的图片</p>
                </div>
              </Upload>
              <div v-for="(file,index) in imgs" :key="index">
                附件：
                <a @click.prevent="downloadFile(file.fileId,file.fileName,index)">{{ file.fileName }} </a>
                <Button type="text" icon="md-trash" @click="deletePicture(file.fileId,'picture')"/>
                <Progress v-show="uploadListVisible[index]" :percent="uploadListPercent[index]"></Progress>
              </div>
            </FormItem>
          </Col>
        </Row>



        <Row v-if="form1datacopy.worksType=='1'" type="flex" justify="space-around" class="code-row-bg">
          <Col span="23">
            <FormItem label="视频："  prop="imgs">
              <Upload
                  type="drag"
                  :show-upload-list="true"
                  :before-upload="beforeUploadVideo"
                  :action="downloadUrl"
                  :max-size="10240"
              >
                <div style="height: 60px">
                  <Icon type="ios-cloud-upload" size="24" style="color: #3399ff"></Icon>
                  <p> 请上传 mp4，avi，rm 格式的视频，大小不超过50MB</p>
                </div>
              </Upload>
              <div v-for="(file,index) in imgs" :key="index">
                附件：
                <a @click.prevent="downloadFile(file.id,file.fileName)">{{ file.fileName }} </a>
                <Button type="text" icon="md-trash" @click="deleteImgs(file.id,'video')"/>
                <Progress v-show="uploadListVisible[index]" :percent="uploadListPercent[index]"></Progress>
              </div>
            </FormItem>
          </Col>
        </Row>

      </Form>
      <div slot="footer">
        <Button @click="submit('form1datacopy')" class="ivu-btn-save" :loading="buttonLoading">确定</Button>
        <Button @click="handleCancel" class="ivu-btn-cancel">取消</Button>
      </div>
    </Modal>
    <Modal title="作品信息详情" :transfer=false v-model="model2" :width=1000 class="modal-view-detail" >
      <Spin fix v-if="showLoading">
        <Icon type="ios-loading" size=18 class="demo-spin-icon-load"></Icon>
        <div>加载中</div>
      </Spin>
      <Row>
        <Col span="24">
          <Form :model="showdata" :label-width="120">
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="7">
                <FormItem label="作品名称：" prop="worksTitle">
                  {{showdata.worksTitle }}
                </FormItem>
              </Col>
              <Col span="7">
                <FormItem label="作品类型：" prop="worksName">
                  {{ showdata.worksName }}
                </FormItem>
              </Col>
              <Col span="7">
                <FormItem label="活动内容：" prop="activityName">
                  {{ showdata.activityName }}
                </FormItem>
              </Col>


            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="7">
                <FormItem label="活动主题：" prop="themeName">
                  {{ showdata.themeName }}
                </FormItem>
              </Col>
              <Col span="7">
                <FormItem label="作者：" prop="createUserName">
                  {{ showdata.createUserName }}
                </FormItem>
              </Col>
              <Col span="7">
                <FormItem label="发布时间：" prop="updateDate">
                  {{ this.formatDate(new Date(showdata.updateDate), 'yyyy-MM-dd') }}
                </FormItem>
              </Col>

            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">

              <Col span="7">
                <FormItem label="浏览量：" prop="browse">
                  {{ showdata.browse }}
                </FormItem>
              </Col>
              <Col span="7">
                <FormItem label="点赞量：" prop="thumbs">
                  {{ showdata.thumbs }}
                </FormItem>
              </Col>
              <Col span="7">

              </Col>

            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="23">
                <FormItem label="所属单位：" prop="orgName">
                  {{ showdata.orgName }}
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="23">
                <FormItem label="描述：" prop="tpshow">
                  <div class="ql-editor" v-html="showdata.tpshow"></div>
                </FormItem>
              </Col>
            </Row>
            <Row v-if="showdata.worksType === '0'" type="flex" justify="space-around" class="code-row-bg">
              <Col span="23">
                <FormItem label="图片：" prop="imgs ">
                                    <span v-for="(file,index) in imgs" :key="index" style="margin-right: 10px">
                                        <div style="width: 25%;height: 25%;">
                                            <router-link target="_blank"
                                                         :to="{path:'/imgDetails',query:{id:file.fileId}}">
                                              {{ file.fileName }}
                                            </router-link>
                                            &emsp;&emsp;
                                            <a @click.prevent="downloadImgFile(file.fileId,file.fileName,index)">下载</a>
                                           <Progress v-show="uploadListVisible[index]"
                                                     :percent="uploadListPercent[index]"></Progress>
                                        </div>
                                    </span>
                </FormItem>
              </Col>
            </Row>
            <Row v-if="showdata.worksType === '1'" type="flex" justify="space-around" class="code-row-bg">
              <Col span="23">
                <FormItem label="视频：" prop="imgs ">
                                    <span v-for="(file,index) in imgs" :key="index" style="margin-right: 10px">
                                        <a @click.prevent="downloadFile(file.id,file.fileName)">{{ file.fileName }}</a>
                                         <Progress v-show="uploadListVisible[index]"
                                                   :percent="uploadListPercent[index]"></Progress>
                                    </span>
                </FormItem>
              </Col>
            </Row>
          </Form>
        </Col>
      </Row>
      <div slot="footer">
        <Button class='ivu-btn-save' @click="model2=false">关闭</Button>
      </div>
    </Modal>
    <Modal title="活动方案选择" :transfer=false footer-hide v-model="activityForSelectModal" :width=900>
      <ActivityForSelect @getActivityData="getActivityData">
      </ActivityForSelect>
      <div slot="footer">
        <Button class='ivu-btn-save' @click="activityForSelectModal=false">关闭</Button>
      </div>
    </Modal>
  </layout>
</template>

<script>
import Quill from "quill";
import ImageResize from "quill-image-resize-module"; // 引用
import {ImageDrop} from "quill-image-drop-module";
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import {Api} from '../../../../api/index.js'
import {quillEditor} from 'vue-quill-editor'
import {sessionStorage} from '../../../../common/cacheUtils.js';
import ActivityForSelect from "../info/activityForSelect";
import DownloadButton from '@/components/download-button';

var cascaderDom = () => import('@/components/cascader-dom.vue');
Quill.register("modules/imageDrop", ImageDrop);
Quill.register("modules/imageResize", ImageResize); // 注册
export default {
  components: {
    quillEditor, ActivityForSelect, cascaderDom, DownloadButton
  },
  data() {
    return {
      upLoad: false,
      exportUrl: Api.activityWorkExport,
      showLoading: false,
      currentUser: sessionStorage('userId').getObject('userId'),
      buttonLoading: false,
      activityType: this.$route.query.type,
      loading: false,
      uploadListVisible: [],
      uploadListPercent: [],
      activityForSelectModal: false,
      title: "",
      token: sessionStorage('token').get('Authorization'),
      upUrl: Api.uploadMongoFileByKeyAndType,
      switchFlag: false,
      form1: {},
      //分页参数
      pageSizeArray: [10, 20, 50],
      imgs: [null, null],
      woksTypeList: [
        {
          name: "图片",
          value: "0",
        },
        {
          name: "视频",
          value: "1",
        },

      ],
      topList: [
        {
          name: "未置顶",
          value: "0",
        },
        {
          name: "审批中",
          value: "1",
        },
        {
          name: "审批驳回",
          value: "2",
        },
        {
          name: "已置顶",
          value: "3",
        }
      ],
      createDate: ["", ""],
      pagedata: {
        total: 0,
        pageSize: 10,
        currentPage: 1,
      },
      editorOption: {
        theme: "snow",
        placeholder: "请输入正文",
        modules: {
          imageDrop: false,
          imageResize: {
            displayStyles: {
              backgroundColor: "black",
              border: "none",
              color: "white"
            },
            modules: ["Resize", "DisplaySize", "Toolbar"]
          },
           // 富文本编辑器配置
          toolbar: {
            container: [
              ["bold", "italic", "underline", "strike"], // 加粗 斜体 下划线 删除线 -----['bold', 'italic', 'underline', 'strike']
              ["blockquote", "code-block"], // 引用  代码块-----['blockquote', 'code-block']
              [{header: 1}, {header: 2}], // 1、2 级标题-----[{ header: 1 }, { header: 2 }]
              [{list: "ordered"}, {list: "bullet"}], // 有序、无序列表-----[{ list: 'ordered' }, { list: 'bullet' }]
              [{script: "sub"}, {script: "super"}], // 上标/下标-----[{ script: 'sub' }, { script: 'super' }]
              [{indent: "-1"}, {indent: "+1"}], // 缩进-----[{ indent: '-1' }, { indent: '+1' }]
              [{direction: "rtl"}], // 文本方向-----[{'direction': 'rtl'}]
              [{size: ["small", false, "large", "huge"]}], // 字体大小-----[{ size: ['small', false, 'large', 'huge'] }]
              [{header: [1, 2, 3, 4, 5, 6, false]}], // 标题-----[{ header: [1, 2, 3, 4, 5, 6, false] }]
              [{color: []}, {background: []}], // 字体颜色、字体背景颜色-----[{ color: [] }, { background: [] }]
              [{font: []}], // 字体种类-----[{ font: [] }]
              [{align: []}], // 对齐方式-----[{ align: [] }]
              ["clean"], // 清除文本格式-----['clean']
              ["image"]

            ],
            handlers: {
              'image': function (value) {
                if (value) {
                  // 调用iview图片上传
                  document.querySelector('.edit-img .ivu-upload .ivu-btn').click()
                } else {
                  this.quill.format('image', false);
                }
              }
            }
          }
        }
      },
      columns1: [
        {
          title: "序号",
          width: 80,
          align: "center",
          fixed: 'left',
          render: (h, params) => {
            if (params.row.id === "-1") return h('span', "汇总");
            return h('span', (params.index) - 1 + (this.pagedata.currentPage - 1) * this.pagedata.pageSize + 1);
          }
        },
        {
          title: '状态',
          align: 'center',
          key: 'status',
          fixed: 'left',
          width: 100,
          render: (h, params) => {
            let color = 'green';
            if (params.row.top == undefined || params.row.top == null || params.row.top == 2 || params.row.top == '0') {
              color = 'red';
            }
            if (params.row.top == 1) {
              color = 'blue';
            }
            return h('div', [
              h('span', {
                style: {
                  color: color
                }
              }, params.row.id == '-1' ? '' : params.row.top == 1 ? '审批中' : params.row.top == 2 ? '审批驳回' : params.row.top == 3 ? '已置顶' : '未置顶' || '--')
            ]);
          }
        },
        {
          minWidth: 300,
          title: '作品名称',
          key: 'worksTitle',
          align: 'center'
        },
        {
          minWidth: 300,
          title: '作品类型',
          key: 'worksType',
          align: 'center',
          render: (h, params) => {
            return h('div', [
              h('span',
                  (params.row.worksType === '0' ? '图片' : params.row.worksType === '1' ? '视频' : ''))
            ]);
          }

        },
        {
          minWidth: 300,
          title: '活动名称',
          key: 'activityName',
          tooltip: true,
          align: 'center'
        },
        {
          minWidth: 300,
          title: '活动主题',
          align: 'center',
          key: 'themeName',
        },


        {
          minWidth: 280,
          title: '作者',
          key: 'createUserName',
          align: 'center'
        },
        {
          minWidth: 280,
          title: '所属单位',
          key: 'orgName',
          align: 'center',
          ellipsis: true
        },
        {
          minWidth: 200,
          title: '发布时间',
          key: 'updateDate',
          sortable: "custom",
          align: 'center',
          render: (h, params) => {
            return h('div', [
              h('span',
                  (params.row['updateDate'] ? this.formatDate(new Date(params.row.updateDate), 'yyyy-MM-dd') : '')
              )]);
          }

        },
        {
          minWidth: 200,
          title: '浏览量',
          key: 'browse',
          align: 'center'
        },
        {
          minWidth: 200,
          title: '点赞量',
          key: 'thumbs',
          align: 'center'
        },

        {
          title: '操作',
          key: 'action',
          fixed: 'right',
          width: 280,
          align: 'center',
          render: (h, params) => {
            if (params.index === 0) {
              return;
            }
            if (params.row.top === '1' || params.row.top === '3') {
              return h('div', [
                h('A', {
                  props: {
                    type: 'primary',
                    size: 'small'
                  },
                  style: {
                    fontSize: '14px'
                  },
                  on: {
                    click: () => {
                      this.showData(params, 1);
                    }
                  }
                }, '详情'),
                h('Divider', {
                  props: {
                    type: 'vertical',
                  }
                }, ''),
                h('A', {
                  props: {type: 'primary', size: 'small'},
                  style: {fontSize: '14px', color: '#c5c8ce', pointerEvents: 'none'}
                }, '申请置顶'),
                h('Divider', {
                  props: {
                    type: 'vertical',
                  }
                }, ''),
                h('A', {
                  props: {type: 'primary', size: 'small'},
                  style: {fontSize: '14px', color: '#c5c8ce', pointerEvents: 'none'}
                }, '修改'),
                h('Divider', {
                  props: {
                    type: 'vertical',
                  }
                }, ''),
                h('A', {
                  props: {type: 'primary', size: 'small'},
                  style: {fontSize: '14px', color: '#c5c8ce', pointerEvents: 'none'}
                }, '删除'),
                h('Divider', {
                  props: {
                    type: 'vertical',
                  }
                }, ''),
                h('A', {
                  props: {type: 'primary', size: 'small'},
                  style: {
                    fontSize: '14px',
                    color: this.currentUser.loginId === this.Common.admin || this.currentUser.userId === params.row.createUserId || this.currentUser.userRole.find(obj => obj.roleId == '73b38b37dff64392ba0ee7dd579bf293' || obj.roleId == 'dda573b123f9472d95ba3063b25133f7') != undefined ||this.currentUser.userBeHandedOver.find(obj => obj == params.row.createUserId) != undefined? 'red' : '#c5c8ce',
                    pointerEvents: this.currentUser.loginId === this.Common.admin || this.currentUser.userId === params.row.createUserId || this.currentUser.userRole.find(obj => obj.roleId == '73b38b37dff64392ba0ee7dd579bf293' || obj.roleId == 'dda573b123f9472d95ba3063b25133f7') != undefined ||this.currentUser.userBeHandedOver.find(obj => obj == params.row.createUserId) != undefined? 'auto' : 'none'
                  },
                  on: {
                    click: () => {
                      this.$Modal.confirm({
                        title: '提示',
                        content: '<p>确定撤销该数据？</p>',
                        onOk: () => {
                          let data = {
                            id: params.row.id,
                            top: 0,
                            updateUserId: this.currentUser.userId
                          }
                          this.$http.post(Api.topActivityWork, data).then((res) => {
                            this.$Message.success("撤销成功")
                            this.query();
                          }).catch(e => {
                            this.$Message.error({
                              content: '撤销失败',
                              duration: 4
                            });
                          })
                        },
                        onCancel: () => {}
                      });
                    }
                  }
                }, '撤销'),

              ]);
            } else {
              if (this.currentUser.loginId === this.Common.admin||this.currentUser.userId === params.row.createUserId || this.currentUser.userRole.find(obj => obj.roleId == '73b38b37dff64392ba0ee7dd579bf293') != undefined||this.currentUser.userBeHandedOver.find(obj => obj == params.row.createUserId) != undefined) {
                return h('div', [
                  h('A', {
                    props: {
                      type: 'primary',
                      size: 'small'
                    },
                    style: {
                      fontSize: '14px'
                    },
                    on: {
                      click: () => {
                        this.showData(params, 1);
                      }
                    }
                  }, '详情'),
                  h('Divider', {
                    props: {
                      type: 'vertical',
                    }
                  }, ''),
                  h('A', {
                    props: {
                      type: 'primary',
                      size: 'small'
                    },
                    style: {
                      fontSize: '14px'
                    },
                    on: {
                      click: () => {
                        this.$Modal.confirm({
                          title: '数据置顶',
                          content: '<p>是否置顶？</p>',
                          okText: '确认',
                          onOk: () => {
                            this.top(params);
                          },
                          cancelText: '取消'
                        });

                      }
                    }
                  }, '申请置顶'),
                  h('Divider', {
                    props: {
                      type: 'vertical',
                    }
                  }, ''),
                  h('A', {
                    props: {
                      type: 'primary',
                      size: 'small'
                    },
                    style: {
                      fontSize: '14px',
                    },
                    on: {
                      click: () => {
                        this.showData(params, 2);
                      }
                    }
                  }, '修改'),
                  h('Divider', {
                    props: {
                      type: 'vertical',
                    }
                  }, ''),
                  h('A', {
                    props: {
                      type: 'primary',
                      size: 'small'
                    },
                    style: {
                      fontSize: '14px',
                      color: 'red'
                    },
                    on: {
                      click: () => {
                        this.$Modal.confirm({
                          title: '数据删除',
                          content: '<p>确定删除该条信息</p>',
                          okText: '确认',
                          onOk: () => {
                            this.deleteData(params);
                          },
                          cancelText: '取消'
                        });
                      }
                    }
                  }, '删除'),
                  h('Divider', {
                    props: {
                      type: 'vertical',
                    }
                  }, ''),
                  h('A', {
                    props: {type: 'primary', size: 'small'},
                    style: {fontSize: '14px', color: '#c5c8ce', pointerEvents: 'none'}
                  }, '撤销')
                ]);
              } else {
                return h('div', [
                  h('A', {
                    props: {
                      type: 'primary',
                      size: 'small'
                    },
                    style: {
                      fontSize: '14px'
                    },
                    on: {
                      click: () => {
                        this.showData(params, 1);
                      }
                    }
                  }, '详情'),
                  h('Divider', {
                    props: {
                      type: 'vertical',
                    }
                  }, ''),
                  h('A', {
                    props: {type: 'primary', size: 'small'},
                    style: {fontSize: '14px', color: '#c5c8ce', pointerEvents: 'none'}
                  }, '申请置顶'),
                  h('Divider', {
                    props: {
                      type: 'vertical',
                    }
                  }, ''),
                  h('A', {
                    props: {type: 'primary', size: 'small'},
                    style: {fontSize: '14px', color: '#c5c8ce', pointerEvents: 'none'}
                  }, '修改'),
                  h('Divider', {
                    props: {
                      type: 'vertical',
                    }
                  }, ''),
                  h('A', {
                    props: {type: 'primary', size: 'small'},
                    style: {fontSize: '14px', color: '#c5c8ce', pointerEvents: 'none'}
                  }, '删除'),
                  h('Divider', {
                    props: {
                      type: 'vertical',
                    }
                  }, ''),
                  h('A', {
                    props: {type: 'primary', size: 'small'},
                    style: {fontSize: '14px', color: '#c5c8ce', pointerEvents: 'none'}
                  }, '撤销')
                ]);
              }
            }
          }
        }
      ],
      ruleCustom: {
        worksTitle: [
          {required: true, message: '  ', trigger: 'blur'}
        ],
        imgs:[
          {
            validator: (rule, value, callback) => {
              if (this.imgs.length == 0 || this.imgs.length == null || this.imgs.length == undefined) {
                callback('请上传附件')
              } else {
                callback()
              }
            },
            required: true,
            trigger: 'change'
          }
        ],
        programmeId: [
          {required: true, message: '  ', trigger: 'change'}
        ],
        activityId: [
          {required: true, message: '  ', trigger: 'change'}
        ],
        worksType: [
          {required: true, message: '  ', trigger: 'change'}
        ],
        tpshow: [
          {required: true, message: '   ', trigger: 'blur'}
        ],
      },
      form1datacopy: {},
      dataTable: [],
      showdata: {},
      model1: false,
      model2: false,
      modelEdit: false,
      add: false,
      tableHeight: 10,
      file: null,
      fileName: null,
      downloadUrl: Api.downloadMongoFile,
      fileFj: '',
      upImg: Api.uploadMongoFile,
      themeList: [],
      activityList: [],
      fileType: 'jpg,jpeg,png',
      minTableHeight: 0


    }
  },
  mounted: function () {
    this.minTableHeight = Number(this.$refs.table.$el.offsetTop);
    this.tableHeight = window.innerHeight - this.$refs.table.$el.offsetTop - 193;

    if (!this.activityType) {
      this.activityType = '1';
    }

    this.query();
    this.selectThemeList();
  },
  methods: {
    amountTo({columns, data}) {
      return this.gAmountTo({columns, data}, ['browse', 'thumbs'])
    },
    getActivityData(row) {
      this.form1datacopy.programmeId = row.programmeId;
      this.form1datacopy.themeName = row.themeName;
      let data = {
        orgId: sessionStorage('userId').getObject('userId').companyId,
        activityThemeId: row.programmeId,
        activityType: this.activityType
      }
      let url = Api.queryActivityMessage;
      this.$http.get(url, {params: data}).then((res) => {
        this.activityList = res.data.data.data;
      }).catch(e => {
        this.$Message.error("数据获取失败")
      })
      this.activityForSelectModal = false;

    },
    activityForSelectIsTrue() {
      this.activityForSelectModal = true;

    },
    uploadExcel(file) {
      let _this = this;
      const files = file;
      let formData = new FormData();
      formData.append("file", files);
      let quill = this.$refs.myTextEditor.quill
      this.$http.put(this.upImg, formData).then((res) => {
        if (res.data.result == "success") {
          // 获取光标所在位置
          let length = quill.getSelection().index;
          // 插入图片，res为服务器返回的图片链接地址
          quill.insertEmbed(length, 'image', Api.downloadMongoFile + "/" +res.data.id)
          // 调整光标到最后
          quill.setSelection(length + 1)
        } else {
          this.$Message.error("图片插入失败");
        }
      }).catch(e => {
        this.$Message.error("附件上传失败");
      });

      return false;

    },
    sortChange(data) {
      if (data.order === 'asc' || data.order === 'desc') {
        let order = data.key
        this.form1.dynamicSort = order + ' ' + data.order
        this.query()
      }
    },
    top(params) {
      let url = Api.topApprovalActivityWork;
      this.$http.get(url + '/' + params.row.id).then((res) => {
        if (res.data.status == 200) {
          this.$Message.success('审批成功');
          this.query()
        } else {
          this.$Message.success('审批失败');
          this.query()
        }

      }).catch(e => {
        this.$Message.error('请求失败' + e);
      })
    },
    switchQuery(flag) {
      this.switchFlag = flag;
      if (this.switchFlag) {
        this.tableHeight = this.tableHeight - 118;
      } else {
        this.tableHeight = this.tableHeight + 118;
      }
    },
    exportBefore(data) {
      let orgId = sessionStorage('userId').getObject('userId').companyId
      data['orgId'] = orgId;
      data['activityType'] = this.$route.query.type;

      if (this.createDate[0] != "" && this.createDate[1] != "") {
        data['startDate'] = this.formatDate(new Date(this.createDate[0]), 'yyyy-MM-dd');
        data['endDate'] = this.formatDate(new Date(this.createDate[1]), 'yyyy-MM-dd');
      }

    },
    selectThemeList() {

      let data = {
        orgId: sessionStorage('userId').getObject('userId').companyId,
        activityType: this.activityType
      }
      let url = Api.queryProgramme;
      this.$http.get(url, {params: data}).then((res) => {
        this.themeList = res.data.data.data;
      }).catch(e => {
        this.$Message.error("数据获取失败")
      })
    },
    selectActivityList(themeId) {
      let data = {
        orgId: sessionStorage('userId').getObject('userId').companyId,
        activityThemeId: themeId,
        activityType: this.activityType
      }
      let url = Api.queryActivityMessage;
      this.$http.get(url, {params: data}).then((res) => {
        this.activityList = res.data.data.data;
      }).catch(e => {
        this.$Message.error("数据获取失败")
      })
    },
    pageChange(pageNum) {
      this.pagedata.currentPage = pageNum;
      this.query();
    },
    pageSizeChange(pageSize) {
      this.pagedata.pageSize = pageSize;
      this.query();
    },
    copyArray(arr) {
      return JSON.parse(JSON.stringify(arr));
    },
    deletePicture(id, type) {
      this.$http.delete(Api.singlePicture + "/" + id).then((res) => {
        if (res.data.result == "success") {
          this.getImgFile(this.form1datacopy.id, type);
        }
      }).catch(e => {
        this.$Message.error("附件上传失败");
      });
    },
    deleteImgs(id, type) {
      this.$http.delete(Api.uploadMongoFile + "/" + id).then((res) => {
        if (res.data.result == "success") {
          this.getImgFile(this.form1datacopy.id, type);
        }
      }).catch(e => {
        this.$Message.error("附件上传失败");
      });
    },
    async beforeUploadImg(file) {
      var index = file.name.lastIndexOf(".");
      var suffix = file.name.substr(index + 1);

      if (suffix != 'jpg' && suffix != 'jpeg' && suffix != 'png') {
        this.$Message.error("请上传jpg,jpeg,png格式的图片");
        this.file = null;
        this.fileName = null;
      } else {
        if (this.imgs.length <= 2) {
          let formData = new FormData();
          formData.append("files", file);
          this.$http.post(Api.interestedPartiesUserFile + "/" + this.form1datacopy.id + "/files/picture", formData).then((res) => {
            if (res.data.result == "success") {
              this.getImgFile(this.form1datacopy.id, "picture");
            } else {
              this.$Message.error("附件上传失败");
            }
          }).catch(e => {
            this.$Message.error("附件上传失败");
          });

        } else {
          this.$Message.error("最多允许上传3张图片");
        }

      }
      return false;
    },
    getImgFile(id, type) {
      this.$http.get(Api.morePicture + "/" + id + "?type=" + type).then((res) => {
        if (res.data.result == "success") {
          this.imgs = res.data.data;
          this.imgs.forEach(item => {
            item.picture = Api.viewPicture + item.filePath;
          })
          console.log(this.imgs);
        }
      }).catch(e => {
        this.$Message.error("文件读取失败");
      });
    },
    selectWorksType(value){
      if (value == '1'){
        this.form1datacopy.tpshow = null;
      }

    },
    getFile(id, type) {
      this.$http.get(Api.interestedPartiesUserFile + "/" + id + "/files/" + type).then((res) => {
        if (res.data.result == "success") {
          this.imgs = res.data.data;
          this.upLoad = false;
          let index = 0;
          this.imgs.forEach(item => {
            this.uploadListPercent[index] = 0;
            this.uploadListVisible[index] = false;
            index++;
          })
        }
      }).catch(e => {
        this.$Message.error("文件读取失败");
      });
    },
    beforeUploadVideo(file) {
      var index = file.name.lastIndexOf(".");
      var suffix = file.name.substr(index + 1);
      if ((suffix != 'mp4' && suffix != 'avi' && suffix != 'rm') || file.size > 1024 * 1024 * 50) {
        this.$Message.error("请上传mp4,avi,rm格式的，小于50MB的视频");
        this.file = null;
        this.fileName = null;
      } else {
        if (!this.upLoad){
          if (this.imgs.length < 1) {
            const files = file;
            let formData = new FormData();
            formData.append("files", files);
            this.upLoad = true;
            this.$http.post(Api.uploadMongoFileByKeyAndType + "/" + this.form1datacopy.id + "/files/video", formData).then((res) => {
              if (res.data.result == "success") {
                this.getFile(this.form1datacopy.id, "video");

              } else {
                this.$Message.error("附件上传失败");
              }
            }).catch(e => {
              this.upLoad = false;
              this.$Message.error("附件上传失败");
            });
          } else {
            this.$Message.error("请先删除视频在上传");
          }

        }else{
          this.$Message.warning("请等待视频上传完成")
        }


      }
      return false;
    },

    showData(data, flag) {
      this.buttonLoading = false;
      this.showLoading = true;
      if (flag == 1) {
        this.$http.get(Api.getActivityWork + "/" + data.row.id).then((res) => {
          this.showdata = res.data.data[0];
          this.showLoading = false;
        }).catch(e => {
          this.$Message.error("获取数据失败");
          this.showLoading = false;
        });
        //查看页面
        this.showdata = data.row;

        if (data.row.worksType === '1') {
          this.showdata.worksName = "视频";
          this.getFile(data.row.id, 'video')
        } else if (data.row.worksType === '0') {
          this.showdata.worksName = "图片";
          this.getImgFile(data.row.id, 'picture')
        } else {
          this.showdata.worksName = "图文";
        }

        this.model2 = true;
      } else {
        //修改页面
        this.$http.get(Api.getActivityWork + "/" + data.row.id).then((res) => {
          this.form1datacopy = res.data.data[0];
          this.showLoading = false;
        }).catch(e => {
          this.$Message.error("获取数据失败");
          this.showLoading = false;
        });
        this.title = "作品信息详情";
        this.selectActivityList(data.row.programmeId);
        this.add = false;
        this.form1datacopy = JSON.parse(JSON.stringify(data.row));
        this.model1 = true;
        if (data.row.worksType == '0') {
          this.getImgFile(data.row.id, 'picture');
        } else if (data.row.worksType == '1') {
          this.getFile(data.row.id, 'video');
        }

      }
    },

    getSelectRows(rows) {
      this.deleteRows = rows;
    },

    deleteData(params) {
      let url = Api.deleteActivityWork;
      this.$http.delete(url + '/' + params.row.id).then((res) => {
        this.$Message.success('成功');
        this.query()
      }).catch(e => {
        this.$Message.error('请求失败' + e);
      })

    },

    query() {
      this.loading = true;
      let data = {
        startPage: this.pagedata.currentPage,
        size: this.pagedata.pageSize,
        orgId: sessionStorage('userId').getObject('userId').companyId,
        activityType: this.activityType
      }
      if (this.createDate[0] != "" && this.createDate[1] != "") {
        this.form1.startDate = this.formatDate(new Date(this.createDate[0]), 'yyyy-MM-dd');
        this.form1.endDate = this.formatDate(new Date(this.createDate[1]), 'yyyy-MM-dd');
      }


      data = Object.assign(data, JSON.parse(JSON.stringify(this.form1)));

      let url = Api.queryActivityWork;
      this.$http.get(url, {params: data}).then((res) => {
        this.dataTable = res.data.data.data;
        // this.dataTable = ;
        if (this.dataTable) {
          this.dataTable.unshift(res.data.data.totalData);
        }
        this.loading = false;
        this.pagedata.total = res.data.data.totalSize;
      }).catch(e => {
        this.$Message.error("数据获取失败")
      })
    },
    reset() {
      this.form1 = {};
      this.createDate = ["", ""];
      if (this.$refs.queryOrgCascader) {
        this.$refs.queryOrgCascader.resetCurrentOrg();
      }
      this.query1();
    },
    query1() {
      console.log(this.$refs.table.$el.offsetTop)
      this.pagedata.currentPage = 1;
      this.query();
    },
    handleCancel() {
      this.form1datacopy = {};
      this.model1 = false;
      this.modelEdit = false;
      this.file = null;
      this.fileName = null;
    },
    submit(name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          this.buttonLoading = true;
          let userId = sessionStorage('userId').getObject('userId').userId;
          let orgId = sessionStorage('userId').getObject('userId').orgInfo.orgId;
          this.form1datacopy.activityType = this.activityType;
          if (this.add) {
            this.form1datacopy.worksAuthor = userId;
            this.form1datacopy.ssdw = orgId;
            this.form1datacopy.createUserId = userId;
            this.form1datacopy.createOrgId = orgId;
            this.form1datacopy.worksTitle = sessionStorage('userId').getObject('userId').companyName+"："+this.form1datacopy.worksTitle;
            this.$http.post(Api.saveActivityWork, this.form1datacopy).then((res) => {
              this.$Message.success("保存成功")
              this.buttonLoading = false;
              this.model1 = false;
              this.query();

            }).catch(e => {
              this.$Message.error({
                content: '保存失败',
                duration: 4
              });
            })

          } else {
            this.form1datacopy.updateUserId = userId;
            this.form1datacopy.updateOrgId = orgId;
            this.$http.post(Api.updateActivityWork, this.form1datacopy).then((res) => {
              this.$Message.success("保存成功")
              this.model1 = false;
              this.buttonLoading = false;
              this.query();
            }).catch(e => {
              this.$Message.error({
                content: '保存失败',
                duration: 4
              });
            })
          }
        } else {
          this.$Message.error('请填报完整!');
        }
      })
    },
    downloadImgFile(fileId, fileName, index) {
      let url = Api.singlePicture + "/" + fileId
      let _this = this;
      this.uploadListVisible[index] = true;
      this.$http.get(url, {
        responseType: 'blob',     //告诉服务器我们需要的响应格式
        progress: function (e) {
          _this.$set(_this.uploadListPercent, index, 100 * (e.loaded / e.total));
        }
      }).then((res) => {
        const aLink = document.createElement("a");
        let blob = new Blob([res.data], {
          type: res.body.type      //将会被放入到blob中的数组内容的MIME类型
        });
        aLink.href = URL.createObjectURL(blob)
        aLink.download = fileName //标题
        aLink.click()
        document.body.appendChild(aLink)
      })
    },
    downloadFile(fileId, fileName, index) {
      let url = this.downloadUrl + "/" + fileId
      let _this = this;
      this.uploadListVisible[index] = true;
      this.$http.get(url, {
        responseType: 'blob',      //告诉服务器我们需要的响应格式
        progress: function (e) {
          _this.$set(_this.uploadListPercent, index, 100 * (e.loaded / e.total));
        }
      }).then((res) => {
        const aLink = document.createElement("a");
        let blob = new Blob([res.data], {
          type: res.body.type      //将会被放入到blob中的数组内容的MIME类型
        });
        aLink.href = URL.createObjectURL(blob)
        aLink.download = fileName //标题
        aLink.click()
        document.body.appendChild(aLink)
      })
    },
    addInfo() {
      this.title = "作品信息新增";
      this.imgs = [];
      this.form1datacopy = {
        id: this.uuid(),
        top: '0',
        worksType:"0",
      };
      this.add = true;
      this.model1 = true;

    },
    formatDate(date, fmt) {
      if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
      }
      let o = {
        'M+': date.getMonth() + 1,
        'd+': date.getDate(),
        'h+': date.getHours(),
        'm+': date.getMinutes(),
        's+': date.getSeconds()
      };
      for (let k in o) {
        if (new RegExp(`(${k})`).test(fmt)) {
          let str = o[k] + '';
          fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : this.padLeftZero(str));
        }
      }
      return fmt;
    },
    padLeftZero(str) {
      return ('00' + str).substr(str.length);
    },
    uuid() {
      let s = [];
      let hexDigits = "0123456789abcdef";
      for (let i = 0; i < 32; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
      }
      s[14] = "4";  // bits 12-15 of the time_hi_and_version field to 0010
      s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);  // bits 6-7 of the clock_seq_hi_and_reserved to 01
      let uuid = s.join("");
      return uuid
    }
  },
}
</script>
<style lang='css' scoped>
@import '../../../../index.css';
.edit-img .ivu-btn{
  display: none;
}
.tableClass {
}

.tableClass >>> .ivu-table td {
  vertical-align: middle;
}

.tableClass >>> .ivu-table th {
  vertical-align: middle;
}

.tableClass >>> .ivu-input-suffix i {
  font-size: 16px;
  line-height: 50px;
  color: #808695;
}

.tableClass >>> .ivu-input {
  border-radius: 0px;
  vertical-align: middle;
  height: 100%;
}

.tableClass >>> textarea.ivu-input {
  height: 100%;
  vertical-align: middle;
}

.tableClass >>> ivu-date-picker {
  height: 100%;
  vertical-align: middle;
}

.tableClass >>> .ivu-table-cell {
  padding-left: 0px;
  padding-right: 0px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: normal;
  word-break: break-all;
  box-sizing: border-box;
  height: 100%;
  /*flex 布局*/
  display: flex;
  /*实现垂直居中*/
  align-items: center;
  /*实现水平居中*/
  justify-content: center;
  text-align: justify;
}

.tableClass >>> .ivu-date-picker {
  height: 100%;
}

.tableClass >>> .ivu-date-picker {
  height: 100%;
}

.tableClass >>> .ivu-input-wrapper {
  height: 100%;
}

.tableClass >>> .ivu-date-picker-rel {
  height: 100%;
}

.tableClass >>> .ivu-input-icon {
  line-height: 50px;
}

.demo-spin-icon-load {
  animation: ani-demo-spin 1s linear infinite;
}

@keyframes ani-demo-spin {
  from {
    transform: rotate(0deg);
  }
  50% {
    transform: rotate(180deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>
